package com.orangelife.mobile.login.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;

import com.bonree.agent.android.Bonree;
import com.bonree.agent.android.harvest.Statistics;
import com.common.jump.CommonJumper;
import com.common.jump.LocationJumper;
import com.common.sp.AppSp;
import com.common.sp.CommSp2;
import com.common.sp.OtherSp;
import com.common.sp.UserSp;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.SystemInfoUtil;
import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.app.service.MyService;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.constants.CommonURL;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.guide.activity.GuideFragmentActivity;
import com.orangelife.mobile.main.biz.JumpUtil;
import com.orangelife.mobile.main.biz.MainHttpBz;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

/**
 * 广告闪屏页，APP第一个界面
 * <p/>
 * Created by YangWei on 2016/3/24.Modify by wgf on 160804.
 *
 * @author yw
 */
public class SplashADActivity extends OrangeLifeBaseActivity {


    @Bind(R.id.ivADBG)
    ImageView ivADBG;
    @Bind(R.id.tvTime)
    TextView tvTime;
    @Bind(R.id.llTime)
    LinearLayout llTime;


    /**
     * 默认广告展示时间
     */
    private int time = 3;
    /**
     * 广告页的URL
     */
    private String adPageUrl;
    /**
     * 是否已点击广告，已点击则关闭定时器
     */
    private boolean hasClickAd;
    private MyService.MyBinder myBinder;

    private boolean isBound;
    private int flag = 0;

    private final String MODULE_NAME = "/app/screenAdv";

    private String title = null;
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyService.MyBinder) service;
            if (CurryApplication.getInstance().isUpdate() && Constant.FIRST_OPEN.equals("0")) {
//                Constant.FIRST_OPEN = "1";
                requestVersion(SplashADActivity.this);
            } else {
                showAndJump();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_ad);
        CurryApplication.getInstance().addActivity(this);
        ButterKnife.bind(this);
        requestCustomerServicePhone();

    }

    /**
     * 数据采集体不要删除
     *
     * @return
     */
    public Map<String, Object> getDataTrack() {
        Map<String, Object> map = new HashMap<>();
        map.put("UI_HOST", DataTrack.APP_NAME);
        map.put("UI_PATH", MODULE_NAME);
        return map;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent startIntent = new Intent(this, MyService.class);
        startService(startIntent);
        bindService();
        initBonree();
        Statistics.onPageStart("Splash1", "SplashPage");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Statistics.onPageEnd("Splash1", "SplashPage");
    }

    /**
     * 请求物业电话
     */
    private void requestCustomerServicePhone() {
        if (TextUtils.isEmpty(CommSp2.getCustomerServicePhone())) {/*如果物业电话为空，则重新请求*/
            MainHttpBz.getCustomerServicePhone();
        }
    }

    public void requestVersion(final Context context) {
        HashMap<String, String> map = new HashMap<>();
        String currentVer = SystemInfoUtil.getVersionName(SplashADActivity.this);
        map.put("type", "2");
        map.put("appType", "1");
        map.put("version", currentVer);
//        map.put("version", "3.1.0");
        VolleyHttpUtil.getInstance().getWithCallback(CommonURL.SPLASHVERSION, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                boolean isSuccess = false;
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject, false)) {
                    Map<String, Object> map = OrangeDataHandler.getMapWithEntityNoGson(jsonObject);
                    if (map != null && map.size() > 0) {
                        isSuccess = true;
                        final String newVersion = String.valueOf(map.get("version"));
                        final String minVersion = String.valueOf(map.get("min_version"));
                        final String url = String.valueOf(map.get("url"));
                        final String versionInfo = String.valueOf(map.get("remark"));
                        final String isForce = String.valueOf(map.get("is_force"));
                        myBinder.check(1, context, isForce, newVersion, minVersion, url, versionInfo, false);
                    }
                }
                if (!isSuccess) {
//                    ToastHelper.getInstance()._toast("获取版本信息失败");
                    showAndJump();
                }
            }
        });
    }


    public void showAndJump() {
        if (StringUtil.isBlank(CommSp2.getCommID()) || !isConnected(false)) {
//            bindService();
            delayedJumpToNextPage();
        } else {
            String commID = CommSp2.getCommID();
            downloadAdImage();
            boolean hasImage = OtherSp.getIsSuccessLoadImg(commID);//判断是否之前成功下载过图片,是的话则显示闪屏广告
            if (hasImage) {
                showAd();
                startShowAdTimer();
                initView();
            } else {
                delayedJumpToNextPage();
            }
        }
    }

    private void downloadAdImage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                myBinder.loadADImage();
            }
        }).start();
    }


    private void initBonree() {
        Bonree.withApplicationToken("8c59e556-e60e-45ac-800f-2b6f12397724").withLocationServiceEnabled(true).start(this);
        Statistics.onMemberId(UserSp.getRegPhone());
    }

    private void initView() {
        ivADBG.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hasClickAd = true;
                showAdHandler.removeCallbacksAndMessages(null);
                jumpToMain();
                Statistics.onEvent("Splash1","Click Ad");
                Map<String, Object> map = new HashMap<>();
                map.put("screenAdvName", title);
                DataTrack.clickTrack("pgScreenAdv", map);
            }
        });
        llTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hasClickAd = true;
                showAdHandler.removeCallbacksAndMessages(null);
                jumpToNextPage();
                Statistics.onEvent("Splash2","Click Next");
            }
        });
//        ivADBG.setEnabled(false);
    }


    /**
     * 启动服务下载当天闪屏页广告
     */
    public void bindService() {
        if (!isBound) {
            Intent intent = new Intent(this, MyService.class);
            isBound = bindService(intent, connection, BIND_AUTO_CREATE);
        }
//        myBinder.loadADImage();
    }


    private String[] parseAdImgInfo(String s) {
        String[] infos = s.split("#");
        return infos;

    }

    /**
     * 展示广告
     */
    private void showAd() {
        String adImgInfo = OtherSp.getAdImgInfo(CommSp2.getCommID());
        String imgInfo[] = parseAdImgInfo(adImgInfo);

        String pics = imgInfo[1]; //取图片的url
        adPageUrl = imgInfo[2];//取点击图片的跳转url
        /*showTime*/
        String showTime = imgInfo[3];//取广告的显示时间
        if (imgInfo.length > 4) {
            title = imgInfo[4];//广告标题
        } else {
            Uri url = Uri.parse(adPageUrl.toUpperCase());
            title = url.getQueryParameter("TITLE");
        }
        if (!TextUtils.isEmpty(showTime)) {
            try {
                time = (int) Double.parseDouble(showTime);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        File file = ImageLoader.getInstance().getDiskCache().get(pics);
        if (file != null) {
            String path = file.getPath();
            Bitmap bitmap = BitmapFactory.decodeFile(path);

            ivADBG.setImageBitmap(bitmap);
            ivADBG.setEnabled(true);
        }
        llTime.setVisibility(View.VISIBLE);
        tvTime.setText("" + time);
    }


    /**
     * 开启广告展示定时器
     */
    private void startShowAdTimer() {
        showAdHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!hasClickAd) {
                    time = time - 1;
                    showAdHandler.obtainMessage(Constant.WHAT_COUNT_DOWN, time)
                            .sendToTarget();
                }
            }
        }, 1000);
    }

    private Handler showAdHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.WHAT_COUNT_DOWN:
                    if (hasClickAd) {
                        return;
                    }
                    if (time > 0) {
                        tvTime.setText("" + time);
                        startShowAdTimer();
                    } else {
                        jumpToNextPage();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 未获取到数据时，延迟跳转
     */
    private void delayedJumpToNextPage() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                jumpToNextPage();
            }
        }, 2000);
    }

    private void jumpToNextPage() {
        if (AppSp.isFirstEnter()) {/*如果是第一次使用，跳到引导页*/
            jumpToGuidePage();
        } else if (StringUtil.isBlank(UserSp.getAccessToken())) {/*如果Token为空，则跳到登录界面*/
            CommonJumper.jumpToLogin(this);
        } else if (StringUtil.isBlank(CommSp2.getCommID())) {/*如果小区ID为空，则跳转到选择小区界面*/
            jumpToSelectCity();
        } else if (isLaunchFromOutside()) {/*从外部启动本APP，带了数据(orangelife://www.com?mode=xx)过来，直接跳转到mode指定的界面*/
            JumpUtil.jumpActivity(this, getIntent().getDataString(), true);
        } else {
            CommonJumper.jumpToMain(this);
        }
        finish(); // 结束启动动画界面
    }

    /**
     * 已经在Manifest.xml中定义了schema，所以可以从外部启动本APP，启动之后，判断DataString，以决定跳转到那个界面，如果没有具体信息，则跳转到主界面
     */
    private boolean isLaunchFromOutside() {
        String scheme = getIntent().getScheme();
        String dataString = getIntent().getDataString();
        Uri jumpModuleUri = null;/*跳转模块信息*/
        if (!StringUtil.isBlank(scheme) && !StringUtil.isBlank(dataString)) {
            jumpModuleUri = Uri.parse(dataString);
        }
        return (jumpModuleUri != null && "orangelife".equals(jumpModuleUri.getScheme()) && "www.com".equals(jumpModuleUri.getHost()));
    }

    /**
     * 跳转到引导页
     */
    private void jumpToGuidePage() {
        IntentHelper.getInstances().getIntent(this,
                GuideFragmentActivity.class); /* 从启动动画ui跳转到主ui */
        AppSp.setIsFirstEnter(false);
    }

    private void jumpToSelectCity() {
        LocationJumper.jumpToSelectCity(this);
    }

    /**
     * 跳转到首页
     */
    private void jumpToMain() {
        CommonJumper.jumpToMain(this, -1, adPageUrl);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onDestroy() {
        if (isBound) {
            unbindService(connection);
        }
        super.onDestroy();
    }

}